import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus
} from '@nestjs/common';
import { Response } from 'express';
// import { HttpAdapterHost } from '@nestjs/core';
import { responseError } from '@/utils/commonResponse';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  constructor() {}

  catch(exception: unknown, host: ArgumentsHost): void {
    const ctx = host.switchToHttp();
    // 获取响应体
    const response = ctx.getResponse<Response>();

    const message =
      exception instanceof HttpException
        ? exception.message
        : exception instanceof Error
          ? exception.stack || exception.message
          : '服务器内部错误!';
    //状态码
    const httpStatus =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    // 自定义异常返回体
    response.status(httpStatus).send(responseError(null, message, httpStatus));
  }
}
